const httpclient = require('../../utils/httpclient.js');
let timer;

// pages/find-address/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    keyword: '',
    infos:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  clear: function(){
    this.setData({
      keyword: '',
      infos: []
    });
  },
  cancel: function(){
    wx.navigateBack({
      
    })
  },
  selectedAddress: function (e){
    let name = e.currentTarget.dataset.name;
    let location = e.currentTarget.dataset.location;
    let locations = location.split(',');
    
    var pages = getCurrentPages();
    var currPage = pages[pages.length - 1];   //当前页面
    var prevPage = pages[pages.length - 2];  //上一个页面
    var addressData = prevPage.data.addressData;
    addressData.address = name;
    addressData.longitude = locations[0];
    addressData.latitude = locations[1];

    //直接调用上一个页面的setData()方法，把数据存到上一个页面中去
    prevPage.setData({
      addressData: addressData
    })
    wx.navigateBack();
  },
  searchAddress: function(e){
    let keyword = e.detail.value;
    let that = this;
    // 比较两次输入的字符串是否一致，不一致保存并查询
    if (keyword != this.data.keyword){
      that.setData({
        keyword: keyword,
        infos:[]
      });
      clearTimeout(timer);

      timer = setTimeout(function(){
        wx.getLocation({
          type: 'wgs84',
          success: function (res) {
            var latitude = res.latitude;
            var longitude = res.longitude;

            httpclient.req(
              "/mall/query_address_by_keyword",
              {
                longitude: longitude,
                latitude: latitude,
                keyword: keyword,
                distance: 10000,
                page_index: 1,
                page_size: 200
              },
              'get',
              function (res) {
                that.setData({
                  infos: res.data.pois
                });
              },
              function (result) {
                console.log(result)
              }
            );
          }
        });
      },1000);
    }
  }
})